from flask import jsonify, request
from pyhanlp import *
def init_routes(app):
    @app.route('/api/title', methods=['GET'])
    def title():
        return jsonify({
            "title": '斗破苍穹知识图谱问答系统'
        })
    @app.route('/api/welcome', methods=['GET'])
    def get_welcome_message():
        return jsonify({
            "message": (
                "欢迎使用斗破苍穹知识图谱问答系统！你可以问我关于斗破苍穹的各种问题。例如：\n"
                "<p>1. 查询人物关系：</p>"
                "<ul>"
                "<li>萧炎的妻子是谁？</li>"
                "<li>萧炎的红颜知己有哪些？</li>"
                "<li>药尘的徒弟是谁？</li>"
                "<li>萧薰儿属于哪个家族？</li>"
                "</ul>"
                "<p>2. 查询势力信息：</p>"
                "<ul>"
                "<li>中州有哪些势力？</li>"
                "<li>魂殿的殿主是谁？</li>"
                "<li>丹塔的巨头有哪些？</li>"
                "<li>星陨阁的阁主是谁？</li>"
                "</ul>"
                "<p>3. 查询家族与敌对关系：</p>"
                "<ul>"
                "<li>远古八族包含哪些家族？</li>"
                "<li>太虚古龙族的族长是谁？</li>"
                "<li>天妖凰族的敌人是谁？</li>"
                "<li>魂族的敌对势力有哪些？</li>"
                "</ul>"
                "请随意提问，我会尽力为你解答！"
            )
        })
    @app.route('/api/query', methods=['GET'])
    def query_knowledge_graph():
        # 获取查询参数
        query = request.args.get('q', '')
        # 这里可以调用知识图谱查询逻辑
        result = process_query(query)
        # 返回结果
        print("查询参数:", query)
        print("查询结果:", result)
        return jsonify({
            "query": query,
            "result": result
        })
def merge_consecutive_nouns(terms):
    merged = []
    i = 0
    n = len(terms)
    while i < n:
        term = terms[i]
        if str(term.nature) in {'n', 'nr', 'nz', 'nnt', 'ng', 'm', 't'}:
            merged_word = term.word
            j = i + 1
            while j < n and str(terms[j].nature) in {'n', 'nr', 'nz', 'nnt', 'ng', 'm', 't'}:
                merged_word += terms[j].word
                j += 1
            merged.append(merged_word)
            i = j
        else:
            i += 1
    return merged
def process_query(query):
    """
    处理查询逻辑：萧炎的妻子是谁？
    """
    from .Neo4jUtils import Neo4jUtils
    neo4j = Neo4jUtils(uri="bolt://localhost:7687", user="neo4j", password="12345678")
    answer = "抱歉，我暂时无法处理该问题。"
    # 进行分词
    segmented = HanLP.segment(query)
    print("分词结果:", segmented)
    extracted = merge_consecutive_nouns(segmented)
    print("提取结果:", extracted)
    # 如果提取到实体和关系，进行查询
    if len(extracted) >= 2:
        entity = extracted[0]
        relation = extracted[1]
        # 调用 get_answer 方法查询
        result = neo4j.get_answer(relation=relation, direction="out", entity=entity)
        if result:
            answer = f"{entity}的{relation}是：{'、'.join(result)}"
        else:
            answer = f"{entity}的{relation}信息暂未收录"

    neo4j.close()
    print("查询结果:", answer)
    return answer
if __name__ == '__main__':
    print(process_query("萧炎的妻子是谁？"))
    print(process_query("中州有哪些势力？"))